package org.linlinjava.litemall.db.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Str {

    public static String EMPTY = "";

    /**
     * if o == "" || o == " " || o == "null"
     * return true;
     *
     * @param o
     * @return
     */
    public static boolean isEmpty(Object o) {
        if (o == null)
            return true;
        if (o instanceof String) {
            String s = (String) o;
            if (s.length() == 0 || s.trim().length() == 0 || "null".equals(s))
                return true;
        }
        return false;
    }

    public static <T> String join(CharSequence delimiter, T[] arr) {
        String[] str = new String[arr.length];
        for (int i = 0; i < arr.length; i++) {
            str[i] = arr[i].toString();
        }
        return String.join(delimiter, str);
    }

    public static List<Integer> idsStrToListInt(String idsStr) {
        String[] ids = idsStr.split(",");
        List<Integer> res = new ArrayList<>(ids.length);
        for (String id : ids) {
            res.add(Integer.parseInt(id));
        }
        return res;
    }

    public static StringBuilder sb() {
        return new StringBuilder();
    }

    public static StringBuilder sb(String s) {
        return new StringBuilder(s);
    }

    public static String toLike(String q) {
        return '%' + q + '%';
    }

    public static String imgToHtml(String imgPath) {
        return "<p><img src=\"" + imgPath + "\" _src=\"" + imgPath + "\" style=\"\"/></p>";
    }


    public static List<String> getImgStr(String htmlStr) {
        List<String> pics = new ArrayList<>();
        String img = "";
        Pattern p_image;
        Matcher m_image;
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />数据
            img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return pics;
    }
}
